<template>
  <div>
    <van-floating-bubble
      axis="xy"
      icon="chat"
      magnetic="x"
      @offset-change="onOffsetChange"
      @click="showSearch"
    />
    <!-- 抽屉 -->
    <van-popup
      v-model:show="showRight"
      position="right"
      close-on-popstate
      :style="{ width: '80%', height: '100%' }"
    >
      <div class="drawer">
        <van-sidebar v-model="active" class="drawer-left">
          <van-sidebar-item
            v-for="item in childrenLayouts"
            :key="item.id"
            :title="item.displayName"
          />
        </van-sidebar>
        <div class="drawer-right">
          <template v-for="(item, index) in childrenLayouts" :key="item.id">
            <component
              v-show="active === index"
              :is="layoutItemSet[item.component]"
              :item="item"
              :isSearch="true"
              ref="childComponentsRef"
            ></component>
          </template>
        </div>
        <div class="drawer-foot">
          <van-button type="default" round>取消</van-button>
          <van-button type="primary" round @click="handleConfirm"
            >确定</van-button
          >
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { layoutItemMap } from "@/components/index";

defineOptions({
  name: "mdSearch",
});

const props = defineProps({
  item: {
    type: Object,
    default: () => {},
  },
});

const layoutItemSet = ref(layoutItemMap.map);

const showRight = ref(false);

const showSearch = () => {
  showRight.value = true;
};

const onOffsetChange = (offset) => {
  showToast(`x: ${offset.x.toFixed(0)}, y: ${offset.y.toFixed(0)}`);
};

// 抽屉逻辑
const active = ref(0);
const childrenLayouts = ref([]);

const childComponentsRef = ref([]);

// 搜索点击确定
const handleConfirm = () => {
  console.log(childComponentsRef.value);
  childComponentsRef.value.forEach((instance) => {
    const { item, value } = instance?.getValue();
    console.log("值打印", item.component, value);
  });
};

onMounted(() => {
  if (props.item.childrenLayouts) {
    childrenLayouts.value = props.item.childrenLayouts;
  }
  const components = document.querySelectorAll('[ref="childComponentsRef"]');
  // 将 NodeList 转换为数组
  const componentInstances = Array.from(components);
  // 存储到响应式引用
  childComponentsRef.value = componentInstances;
});
</script>

<style lang="scss" scoped>
.drawer {
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: auto;
  padding: 8px;
  box-sizing: border-box;
  display: flex;
  position: relative;
  &-left {
    height: calc(100% - 60px);
  }
  &-right {
    flex: 1;
    padding: 4px;
    padding-top: 12px;
    box-sizing: border-box;
    height: calc(100% - 60px);
  }
  &-foot {
    position: absolute;
    bottom: 0%;
    left: 0%;
    width: 100%;
    height: 60px;
    display: flex;
    justify-content: space-around;
    align-items: center;
  }
}
</style>
